//
//  MHRedPacketOrderViewModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/11/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHRedPacketOrderViewModel.h"
#import "MHRedPacketOrderRecordItemViewModel.h"
#import "MHRedHistoryRecord.h"
@implementation MHRedPacketOrderViewModel


- (void)initialize
{
    [super initialize];
    self.title =  LSSTRING("红包记录");
    
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = NO;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    
    
    @weakify(self);
    //圈子列表
    RAC(self, datas) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, datas) map:^(NSArray * datas) {
        @strongify(self)
        return [self dataSourceWithdatas:datas];
    }];
    
    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        NSIndexPath *indexPath = input;
        MHRedHistoryRecord *record =  self.datas[indexPath.row];
        if (record) {
            
            return   [[[self.services.client getNewVideoRecentInfoByHistoryRedWithRecentId:record.recentId] mh_parsedResults] doNext:^(MHAwemeModel *model) {
                MHAwemeListViewModel *viewModel = [[MHAwemeListViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:@[model],@"MHViewModelShowEnterBtn":@false,@"MHViewModelShowSingleVideo":@true}];
                [self.services pushViewModel:viewModel animated:YES];
            }];
            
        }else
        {
            return [RACSignal empty];
        }
    }];

    
}


- (instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params{
    if (self = [super initWithServices:services params:params]) {
        self.type = [params[MHViewModelIDKey] intValue];
        
    }
    return self;
}


- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{

    
    NSArray * (^mapdatas)(NSArray *) = ^(NSArray *products) {
        if (page == 1) {
        } else {
            products = @[(self.datas ?: @[]).rac_sequence, products.rac_sequence].rac_sequence.flatten.array;
        }
        return products;
    };
    return [[[[MHHTTPService sharedInstance] getRedHistoryRecordPagedListWithType:self.type pageNum:page pageSize:self.perPage] mh_parsedResults]  map:mapdatas];
}

#pragma mark - 辅助方法
- (NSArray *)dataSourceWithdatas:(NSArray *)datas {
    if (MHObjectIsNil(datas) || datas.count == 0) return @[];
    NSMutableArray *viewModels = [[datas.rac_sequence map:^(MHRedHistoryRecord *record) {
        record.type = self.type;
        MHRedPacketOrderRecordItemViewModel *viewModel = [[MHRedPacketOrderRecordItemViewModel alloc] initWithModel:record];
//        viewModel.type = self.type;
        return viewModel;
    }].array mutableCopy];
    return viewModels ?: @[] ;
}

@end
